#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded","_direction", "_numconfv", "_newgroup", "_reta", "_vehicles", "_next_pos", "_leader", "_i", "_wp", "_endtime","_path","_road","_roads","_distance","_positions","_i_tries","_next_road"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power","_vgrp","_wp"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	_convoy_started = false;
	_convoy_alive = true;
	_convoy_close_dest = false;
	_convoy_reached_dest = false;
	_convoy_destroyed = false;
	_convoy_arrived = false;
	_random_town = DM_Chapter_Location;
	_random_end = DM_Chapter_LocationEnd;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	_random_end_pos = _random_end select XF_MAP_LOCATION_CENTER;
	_vec_list = DM_VIP;
	_path = DM_Chapter_Data;

	_pos_start = _random_town_pos;
	_pos_end = _random_end_pos;
	_direction = [_random_town_pos, _random_end_pos] call XfDirTo;
	_type_array = _vec_list;
	_side = d_enemy_side;
	if (count _this > 4) then { _side = _this select 4; };
	diag_log Format["(%1)[%2]: %3: %4",diag_tickTime,"chapter1.sqf","Start",_this];
	_crew_member = "";

	_all_towns = [d_map_locations, [XF_MAP_LOCATION_TYPE,"IN",[XF_MAP_LOCATION_TYPE_TOWN,XF_MAP_LOCATION_TYPE_VILLAGE]]] call XfTableFilter;
	
	d_confvdown = 0;
	_numconfv = count _type_array;
	_allSMVecs = [];
	_leader = objNull;
	_roads = _pos_start nearRoads 300;
	_positions = [];
	_i_tries = 30;
	_map_center = getArray (configFile>>"CfgWorlds">>worldName >> "centerPosition");
	_minimum_dist = (((_map_center select 0) max (_map_center select 1)) * 0.4);
	diag_log Format["(%1)[%2]: %3: %4",diag_tickTime,"chapter1.sqf","Path",(count _path)];
	
	if (count _path <= 100) exitWith {
		DM_Mission_Mission_CanRun = false;
		DM_Mission_Chapter_CanRun = false;
		DM_Mission_Chapter_Runs = false;
		false;
	};
	
	_road = _path select 0;
	_i = 1;
	while {count _positions < 12 } do {
		_next_road = _path select _i;
		_distance = (_road distance _next_road);
		if (_distance > 20) then {
			_direction = [_next_road, (_path select (_i + 1))] call XfDirTo;
			_next_pos = _next_road findEmptyPosition [0,10];
			if (count _next_pos <= 0) then { _next_pos = _next_road;};
			_positions set [count _positions, [_next_pos, _direction]];
			_road = _next_road;
		};
		_i = _i + 1;
	};
	diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Positions",_positions,(count _path)];

	_newgroup = [_side] call x_creategroup;
	_newgroup allowFleeing 0;
	_newgroup setCombatMode "GREEN";
	_newgroup setFormation "NONE";
	_newgroup setSpeedMode "NORMAL";
	[0, _newgroup, "Convoy", "MissionFramework"] call ACV_FNCT_PutInStock;

	_vehicles = nil;
	for "_k" from 0 to (_numconfv - 1) do {
		_next_pos = _positions select (count _positions - (1 + _k));
		if (d_mission_debug_messages) then { [format["vec_conv_%1",_k], (_next_pos select 0), "ICON", "ColorRed", [0.5,0.5],"",(_next_pos select 1),"mil_arrow2","",0.7] call XfCreateMarkerLocal; };
		_reta = [1,(_next_pos select 0), (_type_array select _k), _newgroup,0,(_next_pos select 1)] call x_makevgroup;
		diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Created",_reta,(_type_array select _k)];
		_vehicles = _reta select 0;
		(_vehicles select 0) setDir (_next_pos select 1);
		// _next_pos = (getPos (_roads select _k)) findEmptyPosition [0, 10];
		// _next_pos set [2,0];
		// if (count _roads <= (_k + 1)) then {
			// _roads = (_next_pos nearRoads 80) call xfarraypushstack;
		// };
		// [true,[format["pos_%1",_k],_next_pos, "ELLIPSE", "ColorRed", [1,1],"",0,"","",0.7]] call XfMissionMarker;
		{
			_vec = _x;
			_vec setDir (_next_pos select 1);
			_vec addEventHandler ["killed", {d_confvdown = d_confvdown + 1;}];
			[_vec,_newgroup,(getPos _vec),"REGISTER",[]] call XfMissionCreateMissionUnit;
			{
				[_x,_newgroup,(getPos _vec),"REGISTER",[]] call XfMissionCreateMissionUnit;
			} foreach crew _vec;
			_allSMVecs set [count _allSMVecs, _vec];
		} foreach _vehicles;

		_vehicles = nil;
	};

	if (count _allSMVecs < 0) exitWith { 
		DM_Mission_Mission_CanRun = false;
		DM_Mission_Chapter_CanRun = false;
		DM_Mission_Chapter_Runs = false;
		false;
	};

	for [{_i = 0},{_i < count(waypoints _newgroup)},{_i = _i + 1}] do {
		deleteWaypoint [_newgroup, _i];
	};

	_ranks = ["COLONEL","MAJOR","CAPTAIN","LIEUTENANT","SERGEANT","CORPORAL","PRIVATE"];
	for [{_i = 0},{_i < count _allSMVecs}, {_i = _i + 1}] do {
		_driver = driver (_allSMVecs select _i);
		{ _x setRank "PRIVATE";
		} foreach crew (_allSMVecs select _i);
		if (_i < count _ranks) then {
			_driver setRank (_ranks select _i);
		} else {
			_driver setRank "PRIVATE";
		};
		if (_i == 0) then {
			_newgroup selectLeader _driver;
			_leader = _driver;
		};
	};

	_newgroup setCombatMode "RED";
	_newgroup setFormation "COLUMN";
	_newgroup setSpeedMode "NORMAL";

	_wp = _newgroup addWaypoint[getPos (vehicle _leader), 0];
	_wp setWaypointBehaviour "SAFE";
	_wp setWaypointSpeed "NORMAL";
	_wp setwaypointtype "MOVE";
	_wp setWaypointFormation "COLUMN";
	_wp setWaypointCompletionRadius 200;
	_wp setWaypointTimeout [1,1,1];

	sleep 1.658;
	_midway_point = false;
	if (count _path > 150) then {
		_midway_point = true;
		for [{_i = 1},{_i <= 3},{_i = _i + 1}] do {
			_idx = round (((count _path) / 4) * _i);
			if (d_mission_debug_messages) then { [format["vec_path_%1",_idx], (_path select _idx), "ICON", "ColorRed", [0.5,0.5],str(_idx),0,"hd_flag","",0.7] call XfCreateMarkerLocal; };
			_wp = _newgroup addWaypoint[(_path select _idx) , 0];
			_wp setWaypointBehaviour "SAFE";
			_wp setWaypointSpeed "NORMAL";
			_wp setwaypointtype "MOVE";
			_wp setWaypointFormation "COLUMN";
			_wp setWaypointTimeout [1,1,1];
			_wp setWaypointCompletionRadius 200;
			if (_i == 1) then {
				_newgroup setCurrentWaypoint _wp;
			};
		};
	};

	_wp = _newgroup addWaypoint[_pos_end, 0];
	_wp setWaypointBehaviour "SAFE";
	_wp setWaypointSpeed "NORMAL";
	_wp setwaypointtype "MOVE";
	_wp setWaypointFormation "COLUMN";
	_wp setWaypointTimeout [10,15,25];
	_wp setWaypointCompletionRadius 200;
	if (!_midway_point) then { _newgroup setCurrentWaypoint _wp; };

	sleep 20.123;

	private ["_convoy_close_dest","_convoy_reached_dest","_convoy_destroyed"];
	_endtime = time + 3600;

	_numconfv = count _allSMVecs;
	_last_pos = getPos (vehicle (leader _newgroup));
	_target_pos = _pos_end;
	_group_footmen = grpNull;
	_group_created = false;
	
	for [{_i = 0},{_i < count _allSMVecs},{_i = _i + 1}] do {
		_vec = _allSMVecs select _i;
		_vec setVariable ["LastPos", getPos _vec];
		_vec setVariable ["LastTime", time];
	};	
	_spotted = [(_random_town select XF_MAP_LOCATION_UNIQUENAME)];
	_last_spotted = time;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_convoy_alive,_convoy_arrived,_vec_list], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun AND (!_convoy_close_dest) AND (!_convoy_destroyed)} do {
		sleep 10;
		if (X_MP) then {
			if ((call XPlayersNumber) == 0) then {
				if (!d_all_simulation_stopped) then {
					d_all_simulation_stopped = true;
					{_x enableSimulation false} forEach allUnits;
				};
			};
			waitUntil {sleep (1.012 + random 1);(call XPlayersNumber) > 0};
			if (d_all_simulation_stopped) then {
				{_x enableSimulation true} forEach allUnits;
				d_all_simulation_stopped= false;
			};
		};
		
		if (!_convoy_started) then {
			_convoy_started = true;
			["STR_MF_M_CONVOY_START",(_random_town select XF_MAP_LOCATION_DISPLAYNAME)] call XfMissionMessageToAll;
		};
		
		if (d_confvdown == _numconfv) exitWith {
			_convoy_destroyed = true;
		};
		if ({canMove _x} count _allSMVecs == 0) exitWith {
			_convoy_destroyed = true;
		};
		_units = units _newgroup;
		_convoy_close_dest = true;
		{
			if (!isnull _x) then {
				_vec = vehicle _x;
				if (_vec isKindof "Car") then {
					if (canMove _vec && alive _vec && (_vec distance _pos_end) > 300) then {
						_convoy_close_dest = false;
					};
				};
			};
		} foreach _allSMVecs;
		_idx = CurrentWaypoint _newgroup;
		_target_pos = waypointPosition [_newgroup, _idx];
		if ((_last_pos distance (getPos (vehicle (leader _newgroup)))) < 10) then {
			(leader _newgroup) doMove _target_pos;
		};
		{
			_distance = (driver _x) distance (leader _newgroup);
			if (_distance > 300 && ((speed _x) < 5)) then {
				(driver _x) doMove _target_pos;
				sleep 1.4367;
				(driver _x) doFollow (leader _newgroup);
			};
		} foreach _allSMVecs;
		
		// Check for blocked vehicle
		_removed_vec = false;
		for [{_i = 0},{_i < count _allSMVecs},{_i = _i + 1}] do {
			_vec = _allSMVecs select _i;
			if (alive _vec) then {
				_last_pos = _vec getVariable "LastPos";
				_last_time = _vec getVariable "LastTime";
				if ((time - _last_time) > 80) then {
					_vec setVariable ["LastPos", getPos _vec];
					_vec setVariable ["LastTime", time];
					if (!_removed_vec && ((_last_pos distance _vec) < 10)) then {
						diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Blocked vehicle",_vec,(typeof _vec)];
						_allSMVecs set [_i, "XxDelxX"];
						_driver = driver _vec;
						{
							unassignVehicle _x;
							_x leaveVehicle _vec;
						} foreach crew _vec;
						_removed_vec = true;
					};
				};
			};
		};
		_allSMVecs = _allSMVecs - ["XxDelxX"];
		
		// Check that the leader is the driver of an active vehicle
		_leader = leader _newgroup;
		if ((_leader != driver (vehicle _leader)) || (_leader == vehicle _leader)) then {
			_leader_assigned = false;
			for [{_i = 0},{_i < count _allSMVecs},{_i = _i + 1}] do {
				_vec = _allSMVecs select _i;
				if (alive _vec && canMove _vec && count (crew _vec) > 0 && !_leader_assigned) then {
					_newgroup selectLeader (driver _vec);
					diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Leader changed",_vec,(typeof _vec),(leader _newgroup)];
					_leader_assigned = true;
				};
			};
		};
		
		_pos_leader = getPos (vehicle (leader _newgroup));
		{
			_unique = (_x select XF_MAP_LOCATION_UNIQUENAME);
			if (! (_unique in _spotted)) then {
				if ( [_pos_leader, (_x select XF_MAP_LOCATION_CENTER), (_x select XF_MAP_LOCATION_SIZE)] call XfPointInCircle ) then {
					if ((time - _last_spotted) > 180) then {
						["STR_MF_M_CONVOY_SPOTTED",(_x select XF_MAP_LOCATION_DISPLAYNAME)] call XfMissionMessageToAll;
						_last_spotted = time;
					};
					_spotted set [ count _spotted, _unique];
				};
			};
		} foreach _all_towns;
		
		{
			// We move troops which end on foot to another group.
			// This way they don't slow the convoy down.
			if ((_x isKindOf "Man") && !(_x != (vehicle _x))) then {
				if (!_group_created || isnull _group_footmen) then {
					_group_created = true;
					_group_footmen = [_side] call x_creategroup;
					_group_footmen setCombatMode "RED";
					_group_footmen setFormation "COLUMN";
					_group_footmen setSpeedMode "FULL";
					_group_footmen allowFleeing 0;
					_group_footmen setBehaviour "SAFE";
					diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Creating FootGroup",_group_footmen,(units _group_footmen)];
					[0, _group_footmen, "ConvoyFootmen", "MissionFramework"] call ACV_FNCT_PutInStock;
					
					_wp = _group_footmen addWaypoint[_pos_end, 0];
					_wp setWaypointBehaviour "SAFE";
					_wp setWaypointSpeed "FULL";
					_wp setwaypointtype "MOVE";
					_wp setWaypointFormation "COLUMN";
					_wp setWaypointTimeout [10,15,25];
					_wp setWaypointCompletionRadius 200;
					_group_footmen setCurrentWaypoint _wp;
				};
				[_x] joinSilent _group_footmen;
				diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Joining Footmen",_x,(typeof _x)];
				_x doMove _pos_end;
			} else {
				if (group _x == _group_footmen) then {
					diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"chapter1.sqf","Joining Vehicle",_x,(typeof _x)];
					[_x] joinSilent _newgroup;
				};
			};
		} foreach _units;
		
		_last_pos = getPos (vehicle (leader _newgroup));
		if (time > _endtime) exitWith {_convoy_reached_dest = true;};
		sleep 10.123;
	};
	
	if (_convoy_close_dest) then {
		private ["_driver","_crew","_grp","_leader"];
		_wp = _newgroup addWaypoint[_pos_end,0];
		while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun AND (!_convoy_reached_dest) AND (!_convoy_destroyed)} do {
			if (X_MP) then {
				if ((call XPlayersNumber) == 0) then {
					if (!d_all_simulation_stopped) then {
						d_all_simulation_stopped = true;
						{_x enableSimulation false} forEach allUnits;
					};
				};
				waitUntil {sleep (1.012 + random 1);(call XPlayersNumber) > 0};
				if (d_all_simulation_stopped) then {
					{_x enableSimulation true} forEach allUnits;
					d_all_simulation_stopped= false;
				};
			};
			if (d_confvdown == _numconfv) exitWith {_convoy_destroyed = true;};
			_leader = leader _newgroup;
			if (_leader distance _pos_end < 200) exitWith {_convoy_reached_dest = true;};
			if (time > _endtime) exitWith {_convoy_reached_dest = true;};
			{
				(driver _x) doMove _pos_end;
			} foreach _allSMVecs;
			sleep 5;
		};
		sleep 60;
	};
	if (_group_created) then {
		{ deleteVehicle _x;
		} foreach units _group_footmen;
	};
	if (DM_Mission_Chapter_CanRun && DM_Mission_Mission_CanRun) then {
		if (_convoy_reached_dest) then {
			["StopConvoy","", "","",[],"Failed"] call XfMissionTask;
			_chapter_succeeded = false;
		} else {
			["StopConvoy","", "","",[],"Succeeded"] call XfMissionTask;
			_chapter_succeeded = true;
		};
		DM_Mission_Chapter_CanRun = false;
		sleep 30;
	};
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i","_vgrp","_wp"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];
	
	_map_center = getArray (configFile>>"CfgWorlds">>worldName >> "centerPosition");
	_minimum_dist = (((_map_center select 0) max (_map_center select 1)) * 0.4);
	
	_random_town = [];
	_random_end = [];
	_i_tries = 40;
	_current_dist = 0;
	_path = [];
	while { (count _random_town <= 0) && (_i_tries > 0) } do {
		_random_town = [true] call XfMissionGetRandomTown;
		diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing Start:",_random_town];
		if (count _random_town > 0) then {
			_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
			_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
			_random_end_pos = [];
			if ((_random_town_pos distance FLAG_BASE) < 700) then {
				_random_town = [];
			} else {
				_random_end = [];
				_i_tries2 = 20;
				while { (_i_tries2 > 0) } do {
					_random_end_test = [true] call XfMissionGetRandomTown;
					diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing End:",_random_end_test];
					if (count _random_end_test > 0) then {
						_random_end_pos = _random_end_test select XF_MAP_LOCATION_CENTER;
						if ((_random_end_pos distance _random_town_pos) > _minimum_dist || (_random_end_pos distance _random_town_pos) > _current_dist) then {
							_current_dist = (_random_end_pos distance _random_town_pos);
							_random_end = _random_end_test;
						};
					};
					_i_tries2 = _i_tries2 - 1;
				};
				if ((count _random_end) <= 0) then {
					_random_town = [];
				} else {
					_path = [_random_town_pos, _random_end_pos, ((_minimum_dist / 3) max 1000),4000,90] call XfGetRoadPath;
					if (count _path <= 0) then { _random_town = []; };
				};
			};
		};
		_i_tries = _i_tries - 1;
	};
	if ((count _random_town) <= 0) exitWith {"STR_MF_RANDOMTOWNFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	if ((count _path) <= 100) exitWith {"STR_MF_RANDOMTOWNFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_random_end_pos = _random_end select XF_MAP_LOCATION_CENTER;
	DM_Chapter_Location = _random_town;
	DM_Chapter_LocationEnd = _random_end;
	DM_Chapter_Data = _path;
	
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	_random_end_name = _random_end select XF_MAP_LOCATION_DISPLAYNAME;
	diag_log Format["(%1)[%2]: %3: %4 %5 / %6",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Towns:",_random_town, _random_end];
	
	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	
	// Spawn the convoy vehicles.
	// ["T90","T72_RU"],
	// ["BMP3","BRDM2_INS","BMP2_INS","BTR90"],
	// ["BTR90","BRDM2_INS","BRDM2_ATGM_INS"],
	// ["Ural_ZU23_INS","2S6M_Tunguska","Ural_ZU23_INS","ZSU_INS","Ural_ZU23_INS"],
	// ["GAZ_Vodnik","GAZ_Vodnik_HMG","Ural_ZU23_INS"],
	// ["UAZ_MG_INS","UAZ_AGS30_RU","UAZ_MG_INS","UAZ_AGS30_INS","UAZ_MG_INS","UAZ_SPG9_INS","UAZ_MG_INS"],
	// ["KORD","AGS_RU","DSHKM_Ins","2b14_82mm","KORD_high","Metis","DSHkM_Mini_TriPod","SPG9_Ins"],
	// ["ZU23_Ins","Igla_AA_pod_East","ZU23_CDF"],
	// ["D30_RU","GRAD_RU"],
	// ["KamazRefuel"],
	// ["KamazRepair"],
	// ["KamazReammo"]
	_enemy_side_char = switch (d_enemy_side) do {case "EAST": {"E"};case "WEST": {"W"};case "GUER": {"G"};case "CIV": {"G"}; default{"E"};};

	_vehicle_array = missionNamespace getVariable format ["d_veh_a_%1",_enemy_side_char];
	_vec_list = [];
	// One heavy APCs
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_HEAVYAPC) call XfRandomArrayVal)];
	// One light APCs
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTAPC) call XfRandomArrayVal)];
	// One Light Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTWHEEL) call XfRandomArrayVal)];
	// One Heavy Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_HEAVYWHEEL) call XfRandomArrayVal)];
	// One Light Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTWHEEL) call XfRandomArrayVal)];
	// One Ammo Truck
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_AMMO) call XfRandomArrayVal)];
	
	DM_VIP = _vec_list;

	[false,["chapter1_start_cross",_random_town_pos, "ICON", "ColorRed", [1,1],"Start",20,"hd_destroy","",0.8]] call XfMissionMarker;
	[false,["chapter1_end_cross",_random_end_pos, "ICON", "ColorRed", [1,1],"End",20,"hd_destroy","",0.8]] call XfMissionMarker;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_end_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	
	["StopConvoy","STR_MF_M_CONVOY_TASK_DESTROY", ["STR_MF_M_CONVOY_TASK_DESTROY_DESC", _random_town_name,_random_end_name],"",[],"Created"] call XfMissionTask;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"STR_MF_M_CONVOY_SUCCESS" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"STR_MF_MISSIONFAILURE1" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;